<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\PurchaseOrder as PurchaseOrderModel;
use app\admin\model\MaterialPurchaseRequest as PurchaseRequestModel;
use app\admin\model\MaterialStore as MaterialStoreModel;
use app\admin\model\MaterialWarehouse as MaterialWarehouseModel;
use app\admin\model\PackageMaterialStore as PackageMaterialStoreModel;
use app\admin\model\PackageMaterialWarehouse as PackageMaterialWarehouseModel;




/**
 * 
 *
 * @icon fa fa-circle-o
 */
class MaterialReceive extends Backend
{

    /**
     * MaterialReceive模型对象
     * @var \app\admin\model\MaterialReceive
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\MaterialReceive;
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

        /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        $materialWarehouseModel = new MaterialWarehouseModel();
        $packageMaterialWarehouseModel = new PackageMaterialWarehouseModel();
        
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $order_id = $params['order_id'];
        $order_id_data = $this->model->where('order_id', $order_id)->find();
        if (!empty($order_id_data)) {
            return $this->error(__('此采购订单已收货'));
        }
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if (!empty($params['deliverytime'])) {
            $params['deliverytime'] = strtotime($params['deliverytime']);
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        

                // 获取采购订单id
        $order_id = $params['order_id'];
        // 获取采购订单数据
        $order = PurchaseOrderModel::get($order_id);
        if (!$order) {
            $this->error(__('Purchase order does not exist'));
        }else{
            // 获取申购单id
            $purchase_request_id = $order->purchase_request_id;
            if (empty($purchase_request_id)) {
                $this->error(__('Purchase request does not exist'));
            }
            // 获取申购单数据
            $purchase_request = PurchaseRequestModel::get($purchase_request_id);
            if (!$purchase_request) {
                $this->error(__('Purchase request does not exist'));
            }
            // 获取申购单中的物料id
            $material_id = $purchase_request->material_id;
            // 获取申购单中的物料类型
            $material_type = $purchase_request->material_type;
            if (empty($material_id) || empty($material_type)) {
                $this->error(__('Material does not exist'));
            }
            if ($material_type == '原料') {
                // 新增原料入库单
                $material_store = new MaterialStoreModel;
                $material_store->data([
                    'material_receive_id'=> $this->model->id,
                ]);
                $material_store->save();
                // 获取原料入库存中这个原料的数据
                $material_warehouse_data = new MaterialWarehouseModel;
                $material_warehouse_data->data([
                    'material_id' => $material_id,
                    'quantity' => $purchase_request->quantity,
                    'remark' => ''
                ]);
                $material_warehouse_data->save();
            }else if ($material_type == '包材') {
                // 新增包材入库单
                $package_material_store = new PackageMaterialStoreModel;
                $package_material_store->data([
                    'material_receive_id'=> $this->model->id,
                ]);
                $package_material_store->save();
                // 获取包材库存中这个包材的数据
                $package_material_warehouse_data = new PackageMaterialWarehouseModel;
                $package_material_warehouse_data->data([
                    'package_material_id' => $material_id,
                    'quantity' => $purchase_request->quantity,
                    'remark' => ''
                ]);
                $package_material_warehouse_data->save();
                return "包材库存新增成功";
            }
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($params['density'] && $params['thickness']) {
            $params['density'] = '[' . $params['density'] . ']';
            $params['thickness'] = '[' . $params['thickness'] . ']';
            $result = $row->allowField(true)->save($params);
            return $result;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
